package com.bdqn.springbootmybatisplus.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bdqn.springbootmybatisplus.pojo.Book;
import com.bdqn.springbootmybatisplus.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    /**
     * 分页戴条件查询
     * @param pageNum
     * @param size
     * @param book
     * @param model
     * @return
     */

    @RequestMapping("/booksPage")
    public String booksPage(@RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "3")Integer size,Book book, Model model){
        IPage<Book> page = bookService.getPage(pageNum, size,book);
        model.addAttribute("pageInfo",page);
        model.addAttribute("book",book);
        return "index";
    }

    /*
    跳转到新增页面
     */
    @RequestMapping("/add")
    public String addBook(){
        return "addOrUpd";
    }

    /**
     * 新增或修改
     */
    @PostMapping("/savaOrUpdate")
    public String bookAddOrUpd(Book book,Model model){
        if(book.getId()==null){
            bookService.save(book);
        }else {
            bookService.updateById(book);
        }
        return "redirect:/booksPage";
    }

    @GetMapping("/update")
    public String updBook(Integer id,Model model){
        Book book = bookService.getById(id);
        model.addAttribute("bookInfo",book);
        return "addOrUpd";
    }

    //删除
    @RequestMapping("/del")
    public String delBook(Integer id){
        bookService.removeById(id);
        return "redirect:/booksPage";
    }
}
